#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVBoxLayout>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_port = new HSerialPort();
    m_port->open("COM1");
    m_port->start();

    QVBoxLayout *vLayout=new QVBoxLayout();
    ui->centralwidget->setLayout(vLayout);

    {
        m_cbBox=new QComboBox();
        foreach (QextPortInfo info, QextSerialEnumerator::getPorts()) {
            m_cbBox->addItem(info.portName);
        }
        connect(m_port, &HSerialPort::availablePortsChanged,this,&MainWindow::onAvailablePortsChanged);
        vLayout->addWidget(m_cbBox);
    }
    {
        m_btn=new QPushButton("Open");
        connect(m_btn, &QPushButton::clicked,this,&MainWindow::onSerialPortOpenOrClosed);
        vLayout->addWidget(m_btn);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

int MainWindow::write(QByteArray &ucDataArray)
{
    return 0;
}

void MainWindow::onAvailablePortsChanged(QStringList ports)
{
    qDebug() << "availablePortsChanged";
    QString curr_port=m_cbBox->currentText();
    m_cbBox->blockSignals(true);
    m_cbBox->clear();
    m_cbBox->addItems(ports);
    m_cbBox->setCurrentText(curr_port);
    m_cbBox->blockSignals(false);
}

void MainWindow::onSerialPortOpenOrClosed(bool flag)
{
    if(!flag){
        bool rlt=m_port->open(m_cbBox->currentText());
        if(!rlt){
            qDebug()<<"串口打开失败";
            return;
        }
        m_btn->setText("Close");
        qDebug() << "串口已经打开";
    }else{
        m_port->close();
        m_btn->setText("Open");
    }
}
